<template>
	<div class="activities">
		<h2>活动管理</h2>
		<el-button
			class="add-btn"
			icon="el-icon-circle-plus-outline"
			type="primary"
			size="small"
			@click="editActivity = {}"
		>
			发布新活动
		</el-button>
		<div class="table-container">
			<el-table
				ref="table"
				style="width: 100%;"
				stripe
				:data="activities"
			>
				<el-table-column
					label="ID"
					prop="id"
					width="80"
				/>
				<el-table-column
					label="活动名"
					prop="title"
					align="center"
				/>
				<el-table-column
					label="创建人"
					prop="creatorUserId"
					align="center"
				/>
				<el-table-column
					label="有效时间"
					width="170px"
					align="center"
				>
					<template slot-scope="scope">
						<div>{{scope.row.startTime}}</div>
						|
						<div>{{scope.row.endTime}}</div>
					</template>
				</el-table-column>
				<el-table-column
					label="活动介绍"
					align="center"
				>
					<template slot-scope="scope">
						<el-button
							size="mini"
							@click="introMsg=scope.row.intro"
						>
							查看活动介绍
						</el-button>
					</template>
				</el-table-column>
				<el-table-column
					label="兑换码使用情况"
					align="center"
				>
					<template slot-scope="scope">
						{{scope.row.isPasted ? '已过期' : scope.row.codeUsed }} / {{scope.row.codeSum}}
					</template>
				</el-table-column>
				<el-table-column
					label="价值"
					align="center"
				>
					<template slot-scope="scope">
						<div>{{scope.row.exchangeAhaCredit}}Aha币</div>
					</template>
				</el-table-column>
				<el-table-column
					class="btns"
					label="操作"
					align="center"
				>
					<template	slot-scope="scope">
						<!-- 过期或者没有额度了不能继续生成 -->
						<el-button
							size="mini"
							:disabled="scope.row.isPasted || scope.row.codeSum - scope.row.codeUsed<=0"
							@click="getCode(scope.row)"
						>
							生成兑换码
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页器 -->
			<div class="pagination">
				<el-pagination
					background
					layout="prev, pager, next"
					:page-size="pageSize"
					:total="total"
					:current-page="pageNum"
					@current-change="getActivitiesInfo"
				/>
			</div>
		</div>

		<IntroCard
			v-if="introMsg"
			title="活动介绍"
			:html="introMsg"
			@close="introMsg=''"
		/>
		<EditActivity
			v-if="editActivity"
			:activityInfo="editActivity"
			@close="editActivity=null"
			@finish="getActivitiesInfo(1)"
		/>
	</div>
</template>

<script>
import { deleteActivity, getActivity, getCDKEY } from '@operation/api/system'
import EditActivity from './components/EditActivity.vue'
export default {
  route: {
    meta: {
      login: true,
      showLeft: true,
      activeName: 'Activity',
    },
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 15,
      total: 0,
      activities: [],
      introMsg: '',
      editActivity: null
    }
  },
  components: {
    EditActivity
  },
  created() {
    this.getActivitiesInfo(1)
  },
  methods: {
    /* 获取活动信息 */
    async getActivitiesInfo(pageNum = this.pageNum) {
      this.editActivity = null
      const res = await getActivity({
        pageNum,
        pageSize: this.pageSize,
      })

      this.activities = res.data.pageData.map(item => {
        return {
          ...item.activity,
          createTime: moment(item.activity.createTime).format('YYYY/MM/DD HH:mm:ss'),
          startTime: moment(item.activity.startTime).format('YYYY/MM/DD HH:mm:ss'),
          endTime: moment(item.activity.endTime).format('YYYY/MM/DD HH:mm:ss'),
          isPasted: new Date(item.activity.endTime).getTime() - Date.now() < 0, // 是否过期
          codeUsed: item.codeUsed,
        }
      })
      this.pageNum = pageNum
      this.total = res.data.total
      console.log(this.activities)
    },
    /* 生成兑换码 */
    async getCode(activity) {
      const { value } = await this.$prompt('输入兑换码数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\d/,
        inputErrorMessage: '格式错误'
      })

      if (Number(value) > activity.unUse) {
        this.$warn('兑换码数量不足')
      } else {
        const res = await getCDKEY({
          activityId: activity.id,
          count: value
        })

        this.activities[ this.activities.indexOf(activity) ].unUse += Number(value)
        const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(`兑换码\n${ res.data.join('\n') }`)

        const downloadLink = document.createElement('a')

        downloadLink.href = uri
        downloadLink.download = '兑换码.csv'
        document.body.appendChild(downloadLink)
        downloadLink.click()
        document.body.removeChild(downloadLink)

        this.getActivitiesInfo()
      }
    },
    /* 删除活动 */
    removeActivity(activity) {
      this.$confirm('确认删除该活动?', () => {
        deleteActivity(activity.id)
          .then(() => {
            this.$warn('删除成功')
            this.getActivitiesInfo(1)
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.activities {
  position: relative;
  padding: 20px;
  font-size: $sSmall;

  h2 {
    margin-bottom: 10px;
    color: $blue;
  }

  .add-btn {
    position: absolute;
    top: 20px;
    right: 10px;
  }

  .el-table {
    .el-button {
      display: block;
      margin: 5px auto;
    }

    .show-remind {
      margin-top: 10px;
      color: $dark3;
    }
  }

  .pagination {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
